package com.bootdo.system.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;

import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.config.Constant;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.*;
import com.bootdo.system.vo.UserVO;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bootdo.common.domain.Tree;
import com.bootdo.system.dao.DeptDao;
import com.bootdo.system.dao.PayDao;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.dao.UserOldDao;
import com.bootdo.system.dao.UserRoleDao;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.PayDO;
import com.bootdo.system.domain.SuyongDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserRoleDO;
import com.bootdo.system.service.SuyongService;
import com.bootdo.system.service.UserOldService;
import com.bootdo.system.service.UserService;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	UserDao userMapper;
	@Autowired
	UserRoleDao userRoleMapper;
	@Autowired
	DeptDao deptMapper;
	@Autowired
	private FileService sysFileService;
	@Autowired
	private BootdoConfig bootdoConfig;
	@Autowired
	UserOldService useroldService;
	@Autowired
	SuyongService suyongService;
	@Autowired
	private PayDao payDao;
	@Autowired
	private UserOldService userOldService;

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);

	@Override
	public UserDO get(Long id) {
		UserDO user = null;
		try {
			user = useroldService.get(id);
		} catch (Exception e) {
			System.out.println("未登录");
			return null;
		}

		SuyongDO suyongDO = suyongService.get(id);
		if (suyongDO != null) {
			user.setAuthNo(suyongDO.getAuthNo());
			user.setFirstlogin(suyongDO.getFirstlogin());
			user.setFlag(suyongDO.getFlag());
			user.setOldupper(suyongDO.getOldupper());
			user.setStatus(suyongDO.getStatus());
			user.setCity(suyongDO.getCity());
			user.setDistrict(suyongDO.getDistrict());
			user.setProvince(suyongDO.getProvince());
			user.setLiveAddress(suyongDO.getLiveAddress());
		} else {
			user.setLiveAddress("暂无");
			user.setFirstlogin(0);

		}

		return user;

	}

	// 代理充值获取用户对象的方法
	@Override
	public UserDO getIdForAgentPay(Long id) {
		UserDO user = useroldService.get(id);

		return user;

	}

	@Override
	public List<UserDO> list(Map<String, Object> map) {
		return userMapper.list(map);
	}

	@Override
	public List<UserDO> listUser(Map<String, Object> map) {

		return userMapper.listUser(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return userMapper.count(map);
	}

	@Transactional
	@Override
	public int save(UserDO user) {
		// 新增用户添加邀请码
		String code;
		while (true) {
			code = RandomUtils.code();
			Map<String, Object> codeMap = new HashMap<>();
			codeMap.put("inviteCode", code);
			if (userMapper.list(codeMap).size() <= 0) {
				break;
			}

		}
		user.setInviteCode(code);

		user.setAddTime(new Date());
		int count = userMapper.save(user);
		Long userId = user.getId();
		if (user.getRoleIds() != null) {
			List<Long> roles = user.getRoleIds();
			userRoleMapper.removeByUserId(userId);
			List<UserRoleDO> list = new ArrayList<>();
			for (Long roleId : roles) {
				UserRoleDO ur = new UserRoleDO();
				ur.setUserId(userId);
				ur.setRoleId(roleId);
				list.add(ur);
			}
			if (list.size() > 0) {
				userRoleMapper.batchSave(list);
			}

		} else {
			List<Long> roles = new ArrayList<>();
			if (user.getAgencyRank() == Constant.AGENT_ONE || user.getAgencyRank() == Constant.AGENT_TWO
					|| user.getAgencyRank() == Constant.AGENT_THREE) {// 一级二级三级代理
				roles.add((long) Constant.ROLEAGENT_ID);
			} else {
				roles.add((long) Constant.ROLEUSER_ID);
			}
			userRoleMapper.removeByUserId(userId);
			List<UserRoleDO> list = new ArrayList<>();
			for (Long roleId : roles) {
				UserRoleDO ur = new UserRoleDO();
				ur.setUserId(userId);
				ur.setRoleId(roleId);
				list.add(ur);
			}
			if (list.size() > 0) {
				userRoleMapper.batchSave(list);
			}

		}

		return count;

	}

	@Override
	public int update(UserDO user) {
		int r;
		UserDO olduser = new UserDO();
		olduser.setId(user.getId());
		olduser.setWyzMoney(user.getWyzMoney());
		olduser.setAgencyRank(user.getAgencyRank());
		olduser.setMyupper(user.getMyupper());
		olduser.setInviteCode(RandomUtils.code() + user.getId());
		r = useroldService.update(olduser);
		if (r == 1) {
			SuyongDO suyongDO = new SuyongDO();
			suyongDO.setAuthNo(user.getAuthNo());
			suyongDO.setCity(user.getCity());
			suyongDO.setDistrict(user.getDistrict());
			suyongDO.setFirstlogin(user.getFirstlogin());
			suyongDO.setFlag(user.getFlag());
			suyongDO.setUserId(user.getId());
			suyongDO.setLiveAddress(user.getLiveAddress());
			suyongDO.setOldupper(user.getOldupper());
			suyongDO.setProvince(user.getProvince());
			suyongDO.setStatus(user.getStatus());
			suyongDO.setWyzAllmoney(user.getWyzAllmoney());
			if (suyongService.get(user.getId()) != null) {
				suyongService.update(suyongDO);
			} else {
				suyongService.save(suyongDO);
			}

		}

		if (user.getRoleIds() != null) {
			List<Long> roles = user.getRoleIds();
			userRoleMapper.removeByUserId(user.getId());
			List<UserRoleDO> list = new ArrayList<>();
			for (Long roleId : roles) {
				UserRoleDO ur = new UserRoleDO();
				ur.setUserId(user.getId());
				ur.setRoleId(roleId);
				list.add(ur);
			}
			if (list.size() > 0) {
				userRoleMapper.batchSave(list);
			}

		}

		return r;

	}

	// 更新代理充值的方法
	public int updateForAgentPay(UserDO user) {
		int r = useroldService.update(user);

		return r;

	}

	// 更新预存代理充值的方法
	public int updateForAgenterPay(UserDO user) {
		int r;
		if (suyongService.get(user.getId()) != null) {
			SuyongDO suyongDO = new SuyongDO();
			suyongDO.setUserId(user.getId());
			suyongDO.setAuthNo(user.getAuthNo());
			suyongService.update(suyongDO);
			if (user.getRoleIds() != null) {
				List<Long> roles = user.getRoleIds();
				userRoleMapper.removeByUserId(user.getId());
				List<UserRoleDO> list = new ArrayList<>();
				for (Long roleId : roles) {
					UserRoleDO ur = new UserRoleDO();
					ur.setUserId(user.getId());
					ur.setRoleId(roleId);
					list.add(ur);
				}
				if (list.size() > 0) {
					userRoleMapper.batchSave(list);
				}

			}
		}

		r = useroldService.update(user);

		return r;
	}

	@Override
	public int remove(Long userId) {
		return useroldService.remove(userId);

	}

	@Override
	public boolean noexit(Map<String, Object> params) {

		boolean news = userMapper.list(params).size() > 0;
		boolean old = useroldService.list(params).size() > 0;

		if (news == false & old == false) {
			return false;
		} else {
			return true;
		}

	}

	@Override
	public boolean exit(Map<String, Object> params) {
		boolean news;
		boolean old;
		news = userMapper.list(params).size() > 0;
		old = useroldService.list(params).size() > 0;

		if (news == true & old == true) {
			return false;
		} else if (news == true & old == false) {
			return false;
		} else if (news == false & old == true) {
			return false;
		} else {
			return true;
		}

	}

	@Override
	public Set<String> listRoles(Long userId) {
		return null;
	}

	@Override
	public int resetPwd(UserVO userVO, UserDO userDO) throws Exception {
		if (Objects.equals(userVO.getUserDO().getId(), userDO.getId())) {
			if (Objects.equals(MD5Utils.encrypt(userDO.getPhone(), userVO.getPwdOld()), userDO.getPassword())) {
				userDO.setPassword(MD5Utils.encrypt(userDO.getPhone(), userVO.getPwdNew()));
				return userMapper.update(userDO);
			} else {
				throw new Exception("输入的旧密码有误！");
			}
		} else {
			throw new Exception("你修改的不是你登录的账号！");
		}
	}

	@Override
	public int adminResetPwd(UserVO userVO) throws Exception {
		UserDO userDO = get(userVO.getUserDO().getId());
		userDO.setPassword(MD5Utils.encrypt(userDO.getPhone(), userVO.getPwdNew()));
		return userMapper.update(userDO);

	}

	public int batchremove(Long[] userIds) {
		int count = 0;
		for (Long num : userIds) {
			count = useroldService.batchremove(userIds);

		}
		return count;
	}

	@Override
	public Tree<DeptDO> getTree() {
		List<Tree<DeptDO>> trees = new ArrayList<Tree<DeptDO>>();
		List<DeptDO> depts = deptMapper.list(new HashMap<String, Object>(16));
		Long[] pDepts = deptMapper.listParentDept();// 查出dept表的所有部门的父id
		Long[] uDepts = userMapper.listAllDept();// 查出user表的部门id
		Long[] allDepts = (Long[]) ArrayUtils.addAll(pDepts, uDepts);// java两个数组连接在一起
																		// 合并两个数组
		for (DeptDO dept : depts) {
			if (!ArrayUtils.contains(allDepts, dept.getAgencyRank())) {// 检查该数据在数组中是否存在
				continue;
			}
			Tree<DeptDO> tree = new Tree<DeptDO>();
			tree.setId(dept.getAgencyRank().toString());
			tree.setParentId(dept.getParentId().toString());
			tree.setText(dept.getName());
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			state.put("mType", "dept");
			tree.setState(state);
			trees.add(tree);
		}
		List<UserDO> users = userMapper.list(new HashMap<String, Object>(16));
		List<UserDO> list = useroldService.list(new HashMap<String, Object>(16));
		users.addAll(list);

		for (UserDO user : users) {
			Tree<DeptDO> tree = new Tree<DeptDO>();
			tree.setId(user.getId().toString());
			tree.setParentId(user.getAgencyRank() + "");
			tree.setText(user.getCompanyName());
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			state.put("mType", "user");
			tree.setState(state);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		Tree<DeptDO> t = BuildTree.build(trees);
		return t;
	}

	@Override
	public int updatePersonal(UserDO userDO) {

		return userMapper.update(userDO);
	}

	@Override
	public Map<String, Object> updatePersonalImg(MultipartFile file, String avatar_data, Long userId) throws Exception {
		String fileName = file.getOriginalFilename();
		fileName = FileUtil.renameToUUID(fileName);
		FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
		// 获取图片后缀
		String prefix = fileName.substring((fileName.lastIndexOf(".") + 1));
		String[] str = avatar_data.split(",");
		// 获取截取的x坐标
		int x = (int) Math.floor(Double.parseDouble(str[0].split(":")[1]));
		// 获取截取的y坐标
		int y = (int) Math.floor(Double.parseDouble(str[1].split(":")[1]));
		// 获取截取的高度
		int h = (int) Math.floor(Double.parseDouble(str[2].split(":")[1]));
		// 获取截取的宽度
		int w = (int) Math.floor(Double.parseDouble(str[3].split(":")[1]));
		// 获取旋转的角度
		int r = Integer.parseInt(str[4].split(":")[1].replaceAll("}", ""));
		try {
			BufferedImage cutImage = ImageUtils.cutImage(file, x, y, w, h, prefix);
			BufferedImage rotateImage = ImageUtils.rotateImage(cutImage, r);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			boolean flag = ImageIO.write(rotateImage, prefix, out);
			// 转换后存入数据库
			byte[] b = out.toByteArray();
			FileUtil.uploadFile(b, bootdoConfig.getUploadPath(), fileName);
		} catch (Exception e) {
			throw new Exception("图片裁剪错误！！");
		}
		Map<String, Object> result = new HashMap<>();
		if (sysFileService.save(sysFile) > 0) {
			UserDO userDO = new UserDO();
			userDO.setId(userId);

			if (userMapper.update(userDO) > 0) {
				result.put("url", sysFile.getUrl());
			}
		}
		return result;
	}

	@Override
	public int updatePhone(UserDO userDO) {
		// TODO Auto-generated method stub
		return userMapper.updatePhone(userDO);
	}

	public int saveAdmin(UserDO user) {
		user.setMyupper(ShiroUtils.getUserId());
		user.setAddTime(new Date());
		int count = userOldService.save(user);
		return count;

	}

	@Override
	public List<UserDO> listAllUser(String Province) {
		List<UserDO> listAllUser = userMapper.listAllUser(Province);
		return listAllUser;
	}

	@Override
	public List<UserDO> islistUser(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return userMapper.islistUser(map);
	}

	@Override
	public List<UserDO> islistAgency(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return userMapper.islistAgency(map);
	}

}
